package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.StudySystemException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author Tang
 * @version 1.0
 * @date 2023/12/25 01:08
 */
@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    private final CourseMarketMapper courseMarketMapper;
    private final CourseBaseMapper courseBaseMapper;
    private final CourseCategoryMapper courseCategoryMapper;
    public CourseBaseInfoServiceImpl(CourseBaseMapper courseBaseMapper,
                                     CourseMarketMapper courseMarketMapper,
                                     CourseCategoryMapper courseCategoryMapper) {
        this.courseBaseMapper = courseBaseMapper;
        this.courseMarketMapper = courseMarketMapper;
        this.courseCategoryMapper = courseCategoryMapper;
    }

    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,
                                                      PageParams pageParams,
                                                      QueryCourseParamsDto queryCourseParamsDto) {
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        // 根据课程名称查询（模糊查询）
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),
                CourseBase::getName,
                queryCourseParamsDto.getCourseName())
                .eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),
                CourseBase::getAuditStatus,
                queryCourseParamsDto.getAuditStatus())
                .eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),
                CourseBase::getStatus,
                queryCourseParamsDto.getPublishStatus())
                .eq(CourseBase::getCompanyId, companyId);
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());

        Page<CourseBase> basePage = courseBaseMapper.selectPage(page, queryWrapper);
        return new PageResult<>(basePage.getRecords(),
                basePage.getTotal(),
                pageParams.getPageNo(),
                pageParams.getPageSize());
    }

    @Override
    @Transactional
    public CourseBaseInfoDto addCourse(Long companyId, AddCourseDto addCourseDto) {
        CourseBase courseBase = new CourseBase();
        // 只要属性名称一致就拷贝成功
        BeanUtils.copyProperties(addCourseDto, courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        // 默认审核状态：未提交
        courseBase.setAuditStatus("202002");
        // 默认为未发布状态
        courseBase.setStatus("203001");
        int insert = courseBaseMapper.insert(courseBase);
        if (insert <= 0) {
            throw new StudySystemException("添加课程失败");
        }
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        courseMarket.setId(courseBase.getId());
        // 销毁源对象
        addCourseDto = null;
        // 保存课程营销信息
        int saveResult = saveCourseMarket(courseMarket);
        if (saveResult <= 0) {
            throw new StudySystemException("保存课程营销信息错误");
        }
        // 查询课程详细信息
        return selectCourseBaseInfoById(courseMarket.getId());
    }

    public int saveCourseMarket(CourseMarket courseMarket) {
       if (StringUtils.isEmpty(courseMarket.getCharge())) {
           throw new StudySystemException("收费规则为空");
       }
       // 如果收费
       if ("201001".equals(courseMarket.getCharge())) {
           Float price = courseMarket.getPrice();
           if (price == null || price <= 0 || courseMarket.getOriginalPrice() <= 0) {
               StudySystemException.cast("课程价格不能为空或者必须大于0");
           }
       }
       // 如果免费
       if ("201000".equals(courseMarket.getCharge())
       & courseMarket.getPrice() != null
       & courseMarket.getOriginalPrice() != null) {
           courseMarket.setPrice(null);
           courseMarket.setOriginalPrice(null);
       }
       CourseMarket isExist = courseMarketMapper.selectById(courseMarket.getId());
       if (isExist == null) {
          return courseMarketMapper.insert(courseMarket);
       } else {
          BeanUtils.copyProperties(courseMarket, isExist);
          isExist.setId(courseMarket.getId());
          // 销毁源对象
          courseMarket = null;
          return courseMarketMapper.updateById(isExist);
       }
    }

    @Override
    public CourseBaseInfoDto selectCourseBaseInfoById(Long courseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            throw new StudySystemException("课程基础信息为null");
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        if (courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
            courseMarket = null;
        }
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        courseBase = null;

        LambdaQueryWrapper<CourseCategory> queryMt = new LambdaQueryWrapper<>();
        queryMt.eq(CourseCategory::getId, courseBaseInfoDto.getMt())
                .eq(CourseCategory::getIsLeaf, 0);
        CourseCategory categoryMt = courseCategoryMapper.selectOne(queryMt);
        if (categoryMt == null) {
            throw new StudySystemException("未知大分类");
        }
        courseBaseInfoDto.setMtName(categoryMt.getName());

        LambdaQueryWrapper<CourseCategory> querySt = new LambdaQueryWrapper<>();
        querySt.eq(CourseCategory::getId, courseBaseInfoDto.getSt())
                .eq(CourseCategory::getIsLeaf, 1);
        CourseCategory categorySt = courseCategoryMapper.selectOne(querySt);
        if (categorySt == null) {
            throw new StudySystemException("未知小分类");
        }
        courseBaseInfoDto.setStName(categorySt.getName());
        return courseBaseInfoDto;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBaseInfo(Long companyId, EditCourseDto editCourseDto) {
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (null == courseBase) {
            StudySystemException.cast("课程不存在");
        }
        if (!companyId.equals(courseBase.getCompanyId())) {
            StudySystemException.cast("本机构只能修改本机构的课程");
        }
        BeanUtils.copyProperties(editCourseDto, courseBase);
        // 更新修改时间
        courseBase.setChangeDate(LocalDateTime.now());
        int updateBase = courseBaseMapper.updateById(courseBase);
        if (updateBase <= 0) {
            StudySystemException.cast("修改课程基础信息失败");
        }
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        editCourseDto = null;
        CourseMarket isExist = courseMarketMapper.selectById(courseMarket.getId());
        if (isExist == null) {
            int insert = courseMarketMapper.insert(courseMarket);
            if (insert <= 0) {
                StudySystemException.cast("修改课程营销信息失败");
            }
        } else {
            int updateMarket = courseMarketMapper.updateById(courseMarket);
            if (updateMarket <= 0) {
                StudySystemException.cast("修改课程营销信息失败");
            }
        }
        return selectCourseBaseInfoById(courseId);
    }
}
